package com.gui.mianshiya.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gui.mianshiya.common.ErrorCode;
import com.gui.mianshiya.constant.CommonConstant;
import com.gui.mianshiya.exception.BusinessException;
import com.gui.mianshiya.exception.ThrowUtils;
import com.gui.mianshiya.manager.AiManager;
import com.gui.mianshiya.mapper.QuestionMapper;
import com.gui.mianshiya.mapper.WishCollectionMapper;
import com.gui.mianshiya.model.dto.question.QuestionEsDTO;
import com.gui.mianshiya.model.dto.question.QuestionQueryRequest;
import com.gui.mianshiya.model.entity.*;
import com.gui.mianshiya.model.vo.QuestionVO;
import com.gui.mianshiya.model.vo.UserVO;
import com.gui.mianshiya.service.*;
import com.gui.mianshiya.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 题目服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Resource
    private UserService userService;

    @Resource
    private QuestionBankQuestionService questionBankQuestionService;

    @Resource
    private ExerciseRecordsService exerciseRecordsService;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private WishCollectionMapper wishCollectionMapper;

    @Resource
    private MultiQuestionRecordsService multiQuestionRecordsService;

    @Resource
    private AiManager aiManager;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private AiQuestionService  aiQuestionService;

    @Resource
    private QuestionAiService questionAiService;

    /**
     * 校验数据
     *
     * @param question
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validQuestion(Question question, boolean add) {
        ThrowUtils.throwIf(question == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String title = question.getTitle();
        String content = question.getContent();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content)) {
            ThrowUtils.throwIf(content.length() > 10240, ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param questionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = questionQueryRequest.getId();
        Long notId = questionQueryRequest.getNotId();
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        String searchText = questionQueryRequest.getSearchText();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        List<String> tagList = questionQueryRequest.getTags();
        Long userId = questionQueryRequest.getUserId();
        String answer = questionQueryRequest.getAnswer();
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题目封装
     *
     * @param question
     * @param request
     * @return
     */
    @Override
    public QuestionVO getQuestionVO(Question question, HttpServletRequest request) {
        // 对象转封装类
        QuestionVO questionVO = QuestionVO.objToVo(question);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = question.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionVO.setUser(userVO);
        // endregion
        return questionVO;
    }

    /**
     * 分页获取题目封装
     *
     * @param questionPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionVO> questionVOList = questionList.stream().map(question -> {
            return QuestionVO.objToVo(question);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionList.stream().map(Question::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        questionVOList.forEach(questionVO -> {
            Long userId = questionVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionVO.setUser(userService.getUserVO(user));
        });
        // endregion

        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }

    /**
     * 分页获取题目列表
     *
     * @param questionQueryRequest
     * @return
     */
    public Page<Question> listQuestionByPage(QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 题目表的查询条件
        QueryWrapper<Question> queryWrapper = this.getQueryWrapper(questionQueryRequest);
        // 根据题库查询题目列表接口
        Long questionBankId = questionQueryRequest.getQuestionBankId();
        if (questionBankId != null) {
            // 查询题库内的题目 id
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                    .select(QuestionBankQuestion::getQuestionId)
                    .eq(QuestionBankQuestion::getQuestionBankId, questionBankId);
            List<QuestionBankQuestion> questionList = questionBankQuestionService.list(lambdaQueryWrapper);
            if (CollUtil.isNotEmpty(questionList)) {
                // 取出题目 id 集合
                Set<Long> questionIdSet = questionList.stream()
                        .map(QuestionBankQuestion::getQuestionId)
                        .collect(Collectors.toSet());
                // 复用原有题目表的查询条件
                queryWrapper.in("id", questionIdSet);
            }else {
                return new Page<>(current, size,0);
            }
        }
        // 查询数据库
        Page<Question> questionPage = this.page(new Page<>(current, size), queryWrapper);
        return questionPage;
    }

    @Override
    public Page<Question> searchFromEs(QuestionQueryRequest questionQueryRequest) {
        // 获取参数
        Long id = questionQueryRequest.getId();
        Long notId = questionQueryRequest.getNotId();
        String searchText = questionQueryRequest.getSearchText();
        List<String> tags = questionQueryRequest.getTags();
        Long questionBankId = questionQueryRequest.getQuestionBankId();
        Long userId = questionQueryRequest.getUserId();
        // 注意，ES 的起始页为 0
        int current = questionQueryRequest.getCurrent() - 1;
        int pageSize = questionQueryRequest.getPageSize();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();

        // 构造查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 过滤
        boolQueryBuilder.filter(QueryBuilders.termQuery("isDelete", 0));
        if (id != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("id", id));
        }
        if (notId != null) {
            boolQueryBuilder.mustNot(QueryBuilders.termQuery("id", notId));
        }
        if (userId != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("userId", userId));
        }
        if (questionBankId != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("questionBankId", questionBankId));
        }
        // 必须包含所有标签
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("tags", tag));
            }
        }
        // 按关键词检索
        if (StringUtils.isNotBlank(searchText)) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("title", searchText));
            boolQueryBuilder.should(QueryBuilders.matchQuery("content", searchText));
//            boolQueryBuilder.should(QueryBuilders.matchQuery("answer", searchText));
            boolQueryBuilder.minimumShouldMatch(1);
        }
        // 排序
        SortBuilder<?> sortBuilder = SortBuilders.scoreSort();
        if (StringUtils.isNotBlank(sortField)) {
            sortBuilder = SortBuilders.fieldSort(sortField);
            sortBuilder.order(CommonConstant.SORT_ORDER_ASC.equals(sortOrder) ? SortOrder.ASC : SortOrder.DESC);
        }
        // 分页
        PageRequest pageRequest = PageRequest.of(current, pageSize);
        // 构造查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withPageable(pageRequest)
                .withSorts(sortBuilder)
                .build();
        SearchHits<QuestionEsDTO> searchHits = elasticsearchRestTemplate.search(searchQuery, QuestionEsDTO.class);
        // 复用 MySQL 的分页对象，封装返回结果
        Page<Question> page = new Page<>();
        page.setTotal(searchHits.getTotalHits());
        List<Question> resourceList = new ArrayList<>();
        if (searchHits.hasSearchHits()) {
            List<SearchHit<QuestionEsDTO>> searchHitList = searchHits.getSearchHits();
            for (SearchHit<QuestionEsDTO> questionEsDTOSearchHit : searchHitList) {
                resourceList.add(QuestionEsDTO.dtoToObj(questionEsDTOSearchHit.getContent()));
            }
        }
        page.setRecords(resourceList);
        return page;
    }

    @Override
    public List<QuestionVO> getHotQuestionVo() {
        // 1. 获取所有的刷题记录
        List<ExerciseRecords> exerciseRecordsList = exerciseRecordsService.list();
        HashMap<Long, Double> questionScoreMap = new HashMap<>();

        // 2. 计算每个题目的基础分数（基于刷题次数）
        exerciseRecordsList.forEach(record -> {
            Long questionId = record.getQuestionId();
            double score = questionScoreMap.getOrDefault(questionId, 0.0);
            //刷题次数的权重为1.0
            score += record.getTotalCount() * 1.0;
            questionScoreMap.put(questionId, score);
        });

        // 3.获取收藏数据并加入权重
        LambdaQueryWrapper<WishCollection> collectionWrapper = new LambdaQueryWrapper<>();
        collectionWrapper.eq(WishCollection::getIsFlag, 0); // 只查詢有效的收藏
        List<WishCollection> collections = wishCollectionMapper.selectList(collectionWrapper);
        collections.forEach(collection -> {
            Long questionId = collection.getQuestionId();
            double score = questionScoreMap.getOrDefault(questionId, 0.0);
            // 收藏的权重为 2.0
            score += 2.0;
            questionScoreMap.put(questionId, score);
        });

        // 5.将分数转换为列表并排序
        List<Map.Entry<Long, Double>> scoreList = new ArrayList<>(questionScoreMap.entrySet());

      scoreList.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));

        // 6. 获取前12个题目
        List<QuestionVO> questionVOS = new ArrayList<>();
        scoreList.forEach(entry -> {
            if (questionVOS.size() >= 12) {
                return;
            }
            Long questionId = entry.getKey();
            Question question = this.getById(questionId);
            if (question != null) {
                QuestionVO questionVO = new QuestionVO().objToVo(question);
                questionVOS.add(questionVO);
            }
        });

        return questionVOS;
    }

    @Override
    public List<QuestionVO> getHotUserQuestionVo(Long userId) {
        // 1. 獲取用戶收藏的題目
        LambdaQueryWrapper<WishCollection> wishCollectionWrapper = new LambdaQueryWrapper<>();
        wishCollectionWrapper.eq(WishCollection::getIsFlag, 0)
                .eq(WishCollection::getUserId, userId);
        List<WishCollection> wishCollections = wishCollectionMapper.selectList(wishCollectionWrapper);

        // 2. 計算每個題庫的權重分數
        HashMap<Long, Double> questionBankScoreMap = new HashMap<>();
        wishCollections.forEach(wishCollection -> {
            Long questionId = wishCollection.getQuestionId();
            // 獲取題目所屬的題庫
            LambdaQueryWrapper<QuestionBankQuestion> questionBankWrapper = new LambdaQueryWrapper<>();
            questionBankWrapper.eq(QuestionBankQuestion::getQuestionId, questionId);
            List<QuestionBankQuestion> questionBankQuestions = questionBankQuestionService.list(questionBankWrapper);
            // 為每個題庫增加權重
            questionBankQuestions.forEach(questionBankQuestion -> {
                Long questionBankId = questionBankQuestion.getQuestionBankId();
                double score = questionBankScoreMap.getOrDefault(questionBankId, 0.0);
                score += 2.0; // 收藏的權重為 2.0
                questionBankScoreMap.put(questionBankId, score);
            });
        });

        // 3. 獲取用戶刷題記錄
        LambdaQueryWrapper<ExerciseRecords> exerciseRecordsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        exerciseRecordsLambdaQueryWrapper.eq(ExerciseRecords::getUserId, userId);
        List<ExerciseRecords> exerciseRecordsList = exerciseRecordsService.list(exerciseRecordsLambdaQueryWrapper);
        exerciseRecordsList.forEach(record -> {
            Long questionId = record.getQuestionId();
            LambdaQueryWrapper<QuestionBankQuestion> questionBankWrapper = new LambdaQueryWrapper<>();
            questionBankWrapper.eq(QuestionBankQuestion::getQuestionId, questionId);
            List<QuestionBankQuestion> questionBankQuestions = questionBankQuestionService.list(questionBankWrapper);
            questionBankQuestions.forEach(questionBankQuestion -> {
                Long questionBankId = questionBankQuestion.getQuestionBankId();
                double score = questionBankScoreMap.getOrDefault(questionBankId, 0.0);
                score += 1.0; // 刷題權重為 1.0
                questionBankScoreMap.put(questionBankId, score);
            });
        });

        // 4. 獲取用戶在線刷題記錄
        LambdaQueryWrapper<MultiQuestionRecords> multiQuestionRecordsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        multiQuestionRecordsLambdaQueryWrapper.eq(MultiQuestionRecords::getUserId, userId);
        List<MultiQuestionRecords> multiQuestionRecords = multiQuestionRecordsService.list(multiQuestionRecordsLambdaQueryWrapper);
        for (MultiQuestionRecords record : multiQuestionRecords) {
            Long questionBankId = record.getQuestionBankId();
            double score = questionBankScoreMap.getOrDefault(questionBankId, 0.0);
            score += 1.5; // 在線刷題權重為 1.5
            questionBankScoreMap.put(questionBankId, score);
        }

        // 如果用戶沒有任何記錄，使用 getHotQuestionVo 的邏輯
        if (questionBankScoreMap.isEmpty()) {
            return getHotQuestionVo();
        }

        // 5. 將題庫按分數排序
        List<Map.Entry<Long, Double>> scoreList = new ArrayList<>(questionBankScoreMap.entrySet());
        scoreList.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));

        scoreList.forEach(entry -> {
            System.out.println(entry.getKey()+":"+entry.getValue());
        });

        // 6. 從權重最高的題庫中獲取題目
        List<QuestionVO> questionVOS = new ArrayList<>();
        Set<Long> addedQuestionIds = new HashSet<>(); // 用於追踪已添加的題目ID
        int totalQuestionsNeeded = 10; // 總共需要的題目數量

        // 計算每個題庫應該獲取的題目數量
        int[] questionCounts = new int[Math.min(4, scoreList.size())];
        
        // 根據權重分配題目數量
        double totalScore = scoreList.stream()
                .limit(4)
                .mapToDouble(Map.Entry::getValue)
                .sum();

        // 計算每個題庫的基礎題目數量（向下取整）
        int totalBaseCount = 0;
        for (int i = 0; i < questionCounts.length; i++) {
            double score = scoreList.get(i).getValue();
            double proportion = score / totalScore;
            questionCounts[i] = (int) Math.floor(proportion * totalQuestionsNeeded);
            totalBaseCount += questionCounts[i];
        }

        // 分配剩餘的題目（確保總數為10）
        int remainingQuestions = totalQuestionsNeeded - totalBaseCount;
        if (remainingQuestions > 0) {
            // 按照權重比例分配剩餘題目
            for (int i = 0; i < questionCounts.length && remainingQuestions > 0; i++) {
                double score = scoreList.get(i).getValue();
                double proportion = score / totalScore;
                // 計算應該額外分配的題目數量
                int extraCount = (int) Math.ceil(proportion * remainingQuestions);
                // 確保不超過剩餘題目數量
                extraCount = Math.min(extraCount, remainingQuestions);
                questionCounts[i] += extraCount;
                remainingQuestions -= extraCount;
            }
        }
        // 從每個題庫中獲取指定數量的題目
        for (int i = 0; i < questionCounts.length; i++) {
            if (questionVOS.size() >= totalQuestionsNeeded) {
                break;
            }
            Map.Entry<Long, Double> entry = scoreList.get(i);
            Long questionBankId = entry.getKey();
            int targetCount = questionCounts[i];
            // 獲取該題庫的所有題目
            LambdaQueryWrapper<QuestionBankQuestion> questionBankWrapper = new LambdaQueryWrapper<>();
            questionBankWrapper.eq(QuestionBankQuestion::getQuestionBankId, questionBankId);
            List<QuestionBankQuestion> questionBankQuestions = questionBankQuestionService.list(questionBankWrapper);
            // 隨機打亂題目順序
            Collections.shuffle(questionBankQuestions);
            // 從該題庫中獲取指定數量的題目
            int count = 0;
            for (QuestionBankQuestion questionBankQuestion : questionBankQuestions) {
                if (count >= targetCount || questionVOS.size() >= totalQuestionsNeeded) {
                    break;
                }
                Long questionId = questionBankQuestion.getQuestionId();
                if (!addedQuestionIds.contains(questionId)) {
                    Question question = this.getById(questionId);
                    if (question != null) {
                        questionVOS.add(new QuestionVO().objToVo(question));
                        addedQuestionIds.add(questionId);
                        count++;
                    }
                }
            }
        }

        return questionVOS;
    }

    /**
     * AI 生成题目
     *
     * @param questionType 题目类型，比如 Java
     * @param number       题目数量，比如 10
     * @param user         创建人
     * @return ture / false
     */
    @Override
    public Boolean aiGenerateQuestions(String questionType, int number, User user,Long questionBankId) {
        if (ObjectUtil.hasEmpty(questionType, number, user)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        // 1. 定义系统 Prompt
        String systemPrompt = "你是一位专业的程序员面试官，你要帮我生成 {数量} 道 {方向} 面试题，tags为标签请根据题目生成,content为内容根据题目生成,要求输出格式如下：\n" +
                "\n" +
                "1. title:\"Java中的强引用、软引用、弱引用和虚引用有什么区别？\",content:\"解释四种引用类型的特性及使用场景，说明在内存敏感场景中如何选择合适的引用类型\",tags:[\"java\",\"内存管理\",\"引用类型\"]\n" +
                "2. title:\"Java动态代理的实现原理是什么？\",content:\"解析JDK动态代理与CGLIB字节码增强的区别，演示基于接口和类的代理实现方式\",tags:[\"java\",\"反射\",\"设计模式\"]\n" +
                "3. xxxxxx\n" +
                "\n" +
                "除此之外，请不要输出任何多余的内容，不要输出开头、也不要输出结尾，只输出上面的列表。\n" +
                "\n" +
                "接下来我会给你要生成的题目{数量}、以及题目{方向}\n";
        // 2. 拼接用户 Prompt
        String userPrompt = String.format("题目数量：%s, 题目方向：%s", number, questionType);
        // 3. 调用 AI 生成题目
        String answer = aiManager.doChat(systemPrompt, userPrompt);
        // 4. 对题目进行预处理
        // 按行拆分
        List<String> lines = Arrays.asList(answer.split("\n"));
        // 移除序号和 `
        List<Question> questions = lines.stream()
                .map(line -> {
                    // 使用正则表达式提取 title 和 tags
                    Pattern pattern = Pattern.compile("title:\"(.*?)\",content:\"(.*?)\",tags:\\[(.*?)\\]");
                    Matcher matcher = pattern.matcher(line);
                    if (matcher.find()) {
                        String title = matcher.group(1);
                        String content = matcher.group(2);
                        String[] tags = matcher.group(3)  // 获取 "java","多线程","并发" 格式的字符串
                                .replaceAll("\"", "")        // 去除引号
                                .split(",\\s*");             // 按逗号分割（支持空格）
                        Question convert = convert(title,content, tags);
                        convert.setUserId(user.getId());
                        return convert;
                    }
                    return null;
                })
                .filter(q -> q != null)
                .collect(Collectors.toList());
        System.out.println(questions.toString());
        for (Question question : questions) {
             questionMapper.insert(question);
            QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
            questionBankQuestion.setQuestionId(question.getId());
            questionBankQuestion.setQuestionBankId(questionBankId);
            questionBankQuestion.setUserId(user.getId());
            questionBankQuestion.setCreateTime(new Date());
            boolean result = questionBankQuestionService.save(questionBankQuestion);
            String aiQuestion ="";
            try {
                aiQuestion = aiQuestionService.getAiQuestion(question.getTitle());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            QuestionAi questionAi = new QuestionAi();
            questionAi.setQuestionId(question.getId());
            questionAi.setContent(aiQuestion);
            questionAi.setCreateTime(new Date());
            questionAiService.save(questionAi);

            if (!result) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "保存题目失败");
            }
        }

        return true;
    }
    public Question convert(String title, String content, String[] tags) {
        Question question = new Question();
        question.setTitle(title);
        question.setContent(content);
        question.setAnswer(this.aiGenerateQuestionAnswer(title));

        // 将标签数组转为 JSON 字符串
        question.setTags(JSONUtil.toJsonStr(tags));
        return question;
    }

    public static String[] parseTags(Question question) {
        // 将 JSON 字符串解析为字符串数组
        return JSONUtil.parseArray(question.getTags()).toArray(new String[0]);
    }

    private   String aiGenerateQuestionAnswer(String questionTitle) {
        // 1. 定义系统 Prompt
        String systemPrompt = "你是一位专业的程序员面试官，我会给你一道面试题，请帮我生成详细的题解。要求如下：\n" +
                "\n" +
                "1. 题解的语句要自然流畅\n" +
                "2. 题解可以先给出总结性的回答，再详细解释\n" +
                "3. 要使用 Markdown 语法输出\n" +
                "\n" +
                "除此之外，请不要输出任何多余的内容，不要输出开头、也不要输出结尾，只输出题解。\n" +
                "\n" +
                "接下来我会给你要生成的面试题";
        // 2. 拼接用户 Prompt
        String userPrompt = String.format("面试题：%s", questionTitle);
        // 3. 调用 AI 生成题解
        return aiManager.doChat(systemPrompt, userPrompt);
    }
}
